﻿using System.Linq;
using System.Security.Permissions;
using OS.Infrastructure.Domain;
using OS.Infrastructure.Domain.UnitOfWork;
using TaskKernel.Configuration;
using TaskKernel.Domain;
using TaskKernel.Domain.Interface;

namespace TaskWebApplicationUI.PresenterLayer
{
    public class AdminUsersPresenter : AbstractPresenter<IAdminUsersView>
    {
        private readonly ICommandRepository<Account> _command;
        private readonly IQueryAccount _queryAccount;
        private readonly IUnitOfWorkFactory _unitOfWork;

        public AdminUsersPresenter(IQueryAccount queryAccount, IUnitOfWorkFactory unitOfWork, ICommandRepository<Account> command)
        {
            _queryAccount = queryAccount;
            _unitOfWork = unitOfWork;
            _command = command;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = TaskKernelConfiguration.AdminRole)]
        public void OnAddAccount(Account account)
        {
            using (var uow = _unitOfWork.Create()){
                _command.Save(account);
                if (uow.Commit())
                    View.Message = "Запись добавлена";
            }
            OnViewInitialized();
        }

        public void OnViewInitialized()
        {
            using (var uow = _unitOfWork.Create()){
                var accounts = _queryAccount.GetAllAccounts().ToList();
                if (accounts.Any()) View.Accounts = accounts;
            }
        }

        [PrincipalPermission(SecurityAction.Demand, Role = TaskKernelConfiguration.AdminRole)]
        public void OnUpdateAccount(Account account)
        {
            using (var uow = _unitOfWork.Create()){
                var changeAccount = _queryAccount.Get(account.UID);
                changeAccount.UpdateFromView(account);
                _command.Save(changeAccount);
                if (uow.Commit())
                    View.Message = "Запись изменена";
            }
            OnViewInitialized();

        }

        [PrincipalPermission(SecurityAction.Demand, Role = TaskKernelConfiguration.AdminRole)]
        public void OnDeleteAccount(Account account)
        {
            using (var uow = _unitOfWork.Create()){
                var delAccount = _queryAccount.Get(account.UID);
                _command.Delete(delAccount);
                if (uow.Commit())
                    View.Message = "Запись удалена";
                OnViewInitialized();
            }
        }
    }
}